<?php

/**
 * This is the model class for table "orders".
 *
 * The followings are the available columns in table 'orders':
 * @property string $id
 * @property integer $userid
 * @property string $created
 * @property integer $statusid
 * @property string $name
 * @property integer $firmid
 *
 * The followings are the available model relations:
 * @property Orderproducts[] $orderproducts
 * @property Orderstatuses $status
 * @property Ordersincome[] $ordersincomes
 */
class Orders extends CActiveRecord
{
	public $created;
	  public function init()
	{
		$this->created = date("Y-m-d H:i:s");
	}

	
	/**
	 * Returns the static model of the specified AR class.
	 * @return Orders the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'orders';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('created, statusid', 'required'),
			array('userid, statusid, firmid', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>255),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, userid, created, statusid, name, firmid', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'orderproducts' => array(self::HAS_MANY, 'Orderproducts', 'orderid'),
			'status' => array(self::BELONGS_TO, 'Orderstatuses', 'statusid'),
			'ordersincomes' => array(self::HAS_MANY, 'Ordersincome', 'orderid'),
			'firm' => array(self::BELONGS_TO, 'Firms', 'firmid'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'userid' => 'Userid',
			'created' => 'Created',
			'statusid' => 'Statusid',
			'name' => 'Name',
			'firmid' => 'Firm'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria(array("with"=>array("firm","status"),"order"=>"t.id DESC"));

		$criteria->compare('id',$this->id,true);
		$criteria->compare('userid',$this->userid);
		$criteria->compare('created',$this->created,true);
		if(isset($this->firmid)&&$this->firmid<=0) $this->firmid="";
		$criteria->compare('firmid',$this->firmid);
		if(isset($this->statusid)&&$this->statusid<=0) $this->statusid="";
		$criteria->compare('statusid',$this->statusid);
		$criteria->compare('name',$this->name,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	public function form()
	{
		$currentdate = Yii::app()->session->get("currentdate",date('Y-m-d'));
		$prodcountsql = "SELECT orderproducts.productid, orderproducts.count as needed, products.name, (
			SELECT COUNT( store.productid )
			FROM store
			WHERE store.productid = orderproducts.productid
			AND datesell IS NULL
			AND pricesell IS NULL
			) AS prodcount
			FROM orderproducts
			INNER JOIN products ON orderproducts.productid = products.id
			WHERE orderid =".$this->id;	
		$errors = array();
		
		$connection=Yii::app()->db;
		$command=$connection->createCommand($prodcountsql);
		$orderproducts=$command->queryAll(); 
		if(count($orderproducts)>0)
		{
			foreach($orderproducts as $prod)
			{
				if($prod['prodcount']<$prod['needed'])
				{
					$errors[] = "Product {$prod['name']} has {$prod['prodcount']} items ({$prod['needed']} needed)";
				}
			}
		}
		else
		{
			$errors[] = "Немає продуктів";
		}
		if(count($errors)>0)
		{
			return $errors;
		}
		else
		{
			foreach($orderproducts as $prod)
			{
				$command = $connection->createCommand("UPDATE store SET datesell='".$currentdate."', pricesell=0, orderid=".$this->id." WHERE productid='".$prod['productid']."' AND pricesell IS NULL AND datesell IS NULL LIMIT ".$prod['needed']);
				$command->execute();
			}
		}
		
		return true;
	}
}